package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

// tab切换效果
public class MainActivity1 extends AppCompatActivity implements View.OnClickListener{
    Fragment fragment1,fragment2,fragment3,fragment4;
    FragmentManager fm;
    // 设置交互控件的变量
    LinearLayout linearLayout1,linearLayout2,linearLayout3,linearLayout4;

    // Activity的初始化
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        linearLayout1=findViewById(R.id.LinearLayout1);
        linearLayout2=findViewById(R.id.LinearLayout2);
        linearLayout3=findViewById(R.id.LinearLayout3);
        linearLayout4=findViewById(R.id.LinearLayout4);

        fm=getSupportFragmentManager();
        fragment1=new Fragment1();
        fragment2=new Fragment2();
        fragment3=new Fragment3();
        fragment4=new Fragment4();

        initial();
        fragmentshow(fragment1);

        // 在当前类有全局的点击监听
        linearLayout1.setOnClickListener(this);
        linearLayout2.setOnClickListener(this);
        linearLayout3.setOnClickListener(this);
        linearLayout4.setOnClickListener(this);

    }

    // 隐藏不需要显示的content
    private void fragmenthide() {
        FragmentTransaction ft=fm.beginTransaction()
                .hide(fragment1)
                .hide(fragment2)
                .hide(fragment3)
                .hide(fragment4);
        ft.commit();
    }

    // 展示所需要的content
    private void fragmentshow(Fragment fragment) {
        // 先隐藏所有的content，再显示出需要的content
        fragmenthide();
        FragmentTransaction ft=fm.beginTransaction()
                .show(fragment);
        ft.commit();
    }

    // 定义初始化函数
    private void initial() {
        // 把fragment加入content
        FragmentTransaction ft =fm.beginTransaction()
                .add(R.id.content,fragment1)
                .add(R.id.content,fragment2)
                .add(R.id.content,fragment3)
                .add(R.id.content,fragment4);
        // 事务的完整性以提交commit为准
        ft.commit();
    }

    @Override
    public void onClick(View view) {
        // 获取控件变量的id，然后决定点击监听
        if (view.getId()==R.id.LinearLayout1){
            fragmentshow(fragment1);
        }
        if (view.getId()==R.id.LinearLayout2){
            fragmentshow(fragment2);
        }
        if (view.getId()==R.id.LinearLayout3){
            fragmentshow(fragment3);
        }
        if (view.getId()==R.id.LinearLayout4){
            fragmentshow(fragment4);
        }

    }

}